// pages/wo/share/share.js
import request from '../../../utils/http.js'
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    screenWidth: 0, //屏幕宽度 

    personId: 0,
    niCheng: '',
    touXiangUrl: '', //头像

    dianPuId: 0, //店铺id
    ShopName: '', //店铺名称
    ShopLogo: '', //店铺LOGO



    content: '精选商品与您分享', //海报说明
    haiBaoList: [],
    hiddenSharePaper: true, //分享海报的弹框是否隐藏
    linksUrl: '', //分享链接上的图片
    fenXiangPicUrl: 'https://insurancecard.oneplusyang.com/20221222115449a8bdcb1dfe6f4a0abaf6390e2272868c.jpg', //分享链接上的图片
    linksType: 1, //1是logo生成海报  2 其它海报生成


    tempFilePath: '',


    canvasWidth: 0,
    canvasHeight: 0,
    canvasdestWidth: 0,
    canvasdestHeight: 0,
    canvas: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.setData({
      personId: wx.getStorageSync(app.globalData.PERSON_ID),
      touXiangUrl: wx.getStorageSync(app.globalData.TouXiang),
      niCheng: wx.getStorageSync(app.globalData.NiCheng),

      dianPuId: wx.getStorageSync(app.globalData.SHOPID),
      ShopName: wx.getStorageSync(app.globalData.ShopName),
      ShopLogo: wx.getStorageSync(app.globalData.ShopLogo),
    })
    var that = this
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          screenWidth: res.screenWidth
        })
      },
    })

    this.getPageData();
  },





  //获取页面数据
  getPageData: function () {
    var that = this

    wx.request({
      url: app.globalData.base_url + 'qiTa/getFenXiangImageList',
      data: {},
      success: function (res) {
        // console.log("海报:" + JSON.stringify(res.data))
        that.setData({
          haiBaoList: res.data,
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    // console.log('pp' + this.data.fenXiangPicUrl)
    return {
      title: '' + this.data.ShopName,
      imageUrl: this.data.ShopLogo,
      path: '/pages/index/index?tjr_id=' + this.data.personId + '&dianPuId=' + this.data.dianPuId
    }
  },

  //logo生成海报
  bindLogoTap: function (e) {
    wx.showLoading({
      title: '海报生成中...',
    })
    var that = this
    that.setData({
      linksType: 1
    })
    if (that.data.ShopLogo == '' || that.data.ShopLogo == 'undefined') {
      wx.hideLoading();
      wx.showToast({
        title: "未设置店铺Logo，无法生成分享海报", // 提示的内容
        icon: "none", // 图标，默认success
        duration: 3000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    } else {
      that.getWechatCode(that.data.ShopLogo);
    }

  },

  //海报的点击事件
  bindPaperTap: function (e) {
    var index = e.currentTarget.dataset.index;
    var paperUrl = this.data.haiBaoList[index];
    wx.showLoading({
      title: '海报生成中...',
    })
    var that = this
    that.setData({
      linksType: 2
    })
    if (that.data.ShopLogo == '' || that.data.ShopLogo == 'undefined') {
      wx.hideLoading();
      wx.showToast({
        title: "未设置店铺Logo，无法生成分享海报", // 提示的内容
        icon: "none", // 图标，默认success
        duration: 3000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    } else {
      that.getWechatCode(paperUrl);
    }
  },

  //海报关闭
  bindClosePaper: function () {
    this.setData({
      hiddenSharePaper: !this.data.hiddenSharePaper
    })
  },


  //获取微信二维码(用于链接)
  getWechatCode: function (paperUrl) {
    var that = this
    // console.log("二维码生成参数|personId：" + that.data.personId + "scene:" + that.data.dianPuId)
    //var sceneStr = encodeURIComponent(that.data.dianPuId + ',' + that.data.personId)
    var sceneStr = that.data.dianPuId + '_' + that.data.personId
    // console.log("sceneStr：" + sceneStr)
    wx.request({
      url: app.globalData.base_url + 'resource/getQRAndUpToQiNiu',
      data: {
        id: that.data.personId,
        dianPuId: that.data.dianPuId,
        leiXing: 1, //1人的二维码，2产品的二维码
        path: "pages/index/index",
        scene: sceneStr
      },
      success: function (res) {
        console.log("wxerWeiMaUrl:" + JSON.stringify(res.data))
        var wxerWeiMaUrl = res.data.WXErWeiMaUrl;

        if (that.data.linksType == 1) {
          that.createLogoImg(paperUrl, wxerWeiMaUrl, that.data.touXiangUrl);
        } else {
          that.createPapersImg(that.data.ShopLogo, paperUrl, wxerWeiMaUrl, that.data.touXiangUrl);
        }

        

        // wx.getImageInfo({
        //   src: wxerWeiMaUrl,
        //   success: function (res2) {
        //     //console.log("temWxerWeiMaUrl:" + JSON.stringify(res2.path))
        //     var temWxerWeiMaUrl = res2.path;
        //     wx.getImageInfo({
        //       src: paperUrl,
        //       success: function (res3) {
        //         var temPagerUrl = res3.path;
        //         // console.log("temPagerUrl:" + JSON.stringify(res3.path))

        //         wx.getImageInfo({
        //           src: that.data.touXiangUrl,
        //           success: function (res4) {
        //             // console.log("temTouXiangUrl:" + JSON.stringify(res4.path))
        //             var temTouXiangUrl = res4.path;
        //             //logo海报，3张图
        //             if (that.data.linksType == 1) {
        //               that.createLogoImg(temPagerUrl, temWxerWeiMaUrl, temTouXiangUrl);
        //             } else {

        //               //其它非logo海报，需要4张图
        //               wx.getImageInfo({
        //                 src: that.data.ShopLogo,
        //                 success: function (res5) {
        //                   // console.log("tempLogoUrl:" + JSON.stringify(res5.path))
        //                   var tempLogoUrl = res5.path;
        //                   that.createPapersImg(tempLogoUrl, temPagerUrl, temWxerWeiMaUrl, temTouXiangUrl);
        //                 }
        //               })
        //             }

        //           }
        //         })
        //       }
        //     })
        //   }
        // })
      }
    })
  },

  // //绘制Logo海报
  // createLogoImg: function (paperUrl, wxerWeiMaUrl, touXiangUrl) {
  //   var ctx = wx.createCanvasContext('myCanvas');
  //   var scale = this.data.screenWidth / 750;
  //   //总背景
  //   ctx.setFillStyle('white');
  //   ctx.fillRect(0, 0, 580 * scale, 900 * scale);
  //   //头部红色背景
  //   ctx.setFillStyle('#f55659');
  //   ctx.fillRect(0, 0, 580 * scale, 180 * scale);
  //   ctx.save()
  //   let title = {
  //     x: 290 * scale,
  //     y: 290 * scale,
  //     color: '#515151',
  //     size: 36 * scale,
  //     align: 'center',
  //     baseline: 'top',
  //     text: this.data.ShopName,
  //     bold: true
  //   };
  //   this.drawText(ctx, title);


  //   //说明
  //   let content = {
  //     x: 290 * scale,
  //     y: 350 * scale,
  //     color: '#b3b3b3',
  //     size: 26 * scale,
  //     align: 'center',
  //     baseline: 'top',
  //     text: this.data.content,
  //     bold: false
  //   };
  //   this.drawText(ctx, content);

  //   //画logo
  //   ctx.beginPath(); //开始绘制
  //   ctx.arc(290 * scale, 180 * scale, 70 * scale, 0, Math.PI * 2, false);
  //   ctx.clip(); //画了圆 再剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内
  //   ctx.drawImage(paperUrl, 220 * scale, 110 * scale, 140 * scale, 140 * scale); // 推进去图片
  //   ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 可以继续绘制
  //   ctx.save()
  //   // 画二维码
  //   ctx.drawImage(wxerWeiMaUrl, 140 * scale, 400 * scale, 300 * scale, 300 * scale);
  //   ctx.save()
  //   // ctx.drawImage(wxerWeiMaUrl, 332 * scale, 671 * scale, 93 * scale, 93 * scale);

  //   //划虚线
  //   ctx.beginPath()
  //   ctx.setLineDash([8, 4], 2);
  //   ctx.strokeStyle = 'rgb(220,220,220)';
  //   ctx.moveTo(10 * scale, 750 * scale)
  //   ctx.lineTo(570 * scale, 750 * scale)
  //   ctx.stroke()
  //   ctx.save()

  //   //画推荐人
  //   ctx.beginPath(); //开始绘制
  //   ctx.arc(80 * scale, 820 * scale, 50 * scale, 0, Math.PI * 2, false);
  //   ctx.clip(); //画了圆 再剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内
  //   ctx.drawImage(touXiangUrl, 30 * scale, 770 * scale, 100 * scale, 100 * scale); // 推进去图片
  //   ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 可以继续绘制
  //   ctx.save()

  //   //推荐人昵称
  //   let userName = {
  //     x: 150 * scale,
  //     y: 790 * scale,
  //     color: '#b3b3b3',
  //     size: 30 * scale,
  //     align: 'left',
  //     baseline: 'top',
  //     text: this.data.niCheng,
  //     bold: false
  //   };
  //   this.drawText(ctx, userName);

  //   //说明
  //   let tjContent = {
  //     x: 150 * scale,
  //     y: 830 * scale,
  //     color: '#b3b3b3',
  //     size: 24 * scale,
  //     align: 'left',
  //     baseline: 'top',
  //     text: '为您推荐',
  //     bold: false
  //   };
  //   this.drawText(ctx, tjContent);
  //   ctx.draw()
  //   wx.hideLoading();
  //   this.setData({
  //     hiddenSharePaper: !this.data.hiddenSharePaper
  //   })
  // },

  //绘制Logo海报
  createLogoImg: function (paperUrl, wxerWeiMaUrl, touXiangUrl) {


    this.setData({
      hiddenSharePaper: !this.data.hiddenSharePaper
    })
    wx.hideLoading();
    wx.createSelectorQuery()
      .select('#myCanvas') // 在 WXML 中填入的 id
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {

        // console.log("画图:" + JSON.stringify(res))

        const canvas = res[0].node
        // Canvas 画布的实际绘制宽高
        const renderWidth = res[0].width
        const renderHeight = res[0].height
        console.log(renderWidth)
        // Canvas 绘制上下文
        const ctx = canvas.getContext('2d')

        // 初始化画布大小
        const dpr = wx.getWindowInfo().pixelRatio
        // console.log("dpr:" + dpr)
        canvas.width = renderWidth * dpr
        canvas.height = renderHeight * dpr

        var scale = (renderWidth / 580) * dpr;
        console.log('scale:' + scale)
        this.setData({
          canvas: canvas,
          canvasWidth: renderWidth,
          renderHeight: renderHeight,
          canvasdestWidth: renderWidth * dpr,
          canvasdestHeight: renderHeight * dpr,
        })

        // ctx.scale(dpr, dpr)

        ctx.fillStyle = "white";
        ctx.fillRect(0, 0, 580 * scale, 920 * scale);


        ctx.fillStyle = '#f55659'
        ctx.fillRect(0, 0, 580 * scale, 150 * scale);
        // ctx.save()   
        // ctx.font="30px Georgia";
        // ctx.fillText(that.data.ShopName,200* dpr,200* dpr);

        ctx.beginPath();
        ctx.lineWidth = "1";
        ctx.strokeStyle = "rgb(220,220,220)"; // Green path
        ctx.moveTo(0, 790 * scale);
        ctx.lineTo(580 * scale, 790 * scale);
        ctx.stroke(); // Draw it



        //画logo

        const image = canvas.createImage();
        image.src = paperUrl;
        image.onload = () => {
          // 将图片绘制到 canvas 上
          ctx.save()
          ctx.beginPath(); //开始绘制
          // ctx.strokeStyle="white"
          ctx.arc(290 * scale, 150 * scale, 80 * scale, 0, Math.PI * 2, false);
          // ctx.stroke();
          ctx.clip(); //画了圆 再剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内
          ctx.drawImage(image, 210 * scale, 70 * scale, 160 * scale, 160 * scale)
          ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 可以继续绘制
        }

        var shopNameSize = 36 * scale
        var shopNameSizestr = shopNameSize + 'px Arial'

        let title = {
          x: 290 * scale,
          y: 270 * scale,
          color: '#515151',
          size: shopNameSizestr,
          align: 'center',
          baseline: 'top',
          text: this.data.ShopName,
          bold: true
        };
        this.drawText(ctx, title);

        var shopSMSize = 20 * scale
        var shopSMSizestr = shopSMSize + 'px Arial'

        //说明
        let content = {
          x: 290 * scale,
          y: 320 * scale,
          color: '#b3b3b3',
          size: shopSMSizestr,
          align: 'center',
          baseline: 'top',
          text: this.data.content,
          bold: false
        };
        this.drawText(ctx, content);

        ctx.save()
        //画二维码        
        const imageCode = canvas.createImage();
        imageCode.src = wxerWeiMaUrl;
        imageCode.onload = () => {
          ctx.drawImage(imageCode, 100 * scale, 380 * scale, 380 * scale, 380 * scale)

        }



        //画推荐人头像      
        const imageTouX = canvas.createImage();
        imageTouX.src = touXiangUrl;
        imageTouX.onload = () => {
          // 将图片绘制到 canvas 上
          ctx.save()
          ctx.beginPath(); //开始绘制
          // ctx.strokeStyle="white"
          ctx.arc(80 * scale, 854 * scale, 50 * scale, 0, Math.PI * 2, false);
          // ctx.stroke();
          ctx.clip(); //画了圆 再剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内
          ctx.drawImage(imageTouX, 30 * scale, 804 * scale, 100 * scale, 100 * scale)
          ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 可以继续绘制

        }

        var tjrNameSize = 26 * scale
        var tjrNameSizestr = tjrNameSize + 'px Arial'

        //推荐人昵称
        let userName = {
          x: 144 * scale,
          y: 830 * scale,
          color: '#838080',
          size: tjrNameSizestr,
          align: 'left',
          baseline: 'top',
          text: this.data.niCheng,
          bold: false
        };
        this.drawText(ctx, userName);

        //推荐说明
        var tjrSMSize = 20 * scale
        var tjrSMSizestr = tjrSMSize + 'px Arial'

        let tjContent = {
          x: 144 * scale,
          y: 866 * scale,
          color: '#b3b3b3',
          size: tjrSMSizestr,
          align: 'left',
          baseline: 'top',
          text: '为您推荐',
          bold: false
        };
        this.drawText(ctx, tjContent);
      })

  },

  //绘制海报
  createPapersImg: function (logoUrl, paperUrl, wxerWeiMaUrl, touXiangUrl) {
    this.setData({
      hiddenSharePaper: !this.data.hiddenSharePaper
    })

    wx.hideLoading();
    wx.createSelectorQuery()
      .select('#myCanvas') // 在 WXML 中填入的 id
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {

        console.log("画图:" + JSON.stringify(res))

        const canvas = res[0].node
        // Canvas 画布的实际绘制宽高
        const renderWidth = res[0].width
        const renderHeight = res[0].height
        console.log(renderWidth)
        // Canvas 绘制上下文
        const ctx = canvas.getContext('2d')

        // 初始化画布大小
        const dpr = wx.getWindowInfo().pixelRatio
        console.log("dpr:" + dpr)
        canvas.width = renderWidth * dpr
        canvas.height = renderHeight * dpr

        var scale = (renderWidth / 580) * dpr;
        // console.log('scale:' + scale)
        this.setData({
          canvas: canvas,
          canvasWidth: renderWidth,
          renderHeight: renderHeight,
          canvasdestWidth: renderWidth * dpr,
          canvasdestHeight: renderHeight * dpr,
        })

        // ctx.scale(dpr, dpr)

        ctx.fillStyle = "white";
        ctx.fillRect(0, 0, 580 * scale, 920 * scale);


        ctx.fillStyle = '#f55659'
        ctx.fillRect(0, 0, 580 * scale, 180 * scale);
        // ctx.save()   
        // ctx.font="30px Georgia";
        // ctx.fillText(that.data.ShopName,200* dpr,200* dpr);

        ctx.beginPath();
        ctx.lineWidth = "1";
        ctx.strokeStyle = "rgb(220,220,220)"; // Green path
        ctx.moveTo(0, 760 * scale);
        ctx.lineTo(580 * scale, 760 * scale);
        ctx.stroke(); // Draw it



        //画logo

        const image = canvas.createImage();
        image.src = logoUrl;
        image.onload = () => {
          // 将图片绘制到 canvas 上
          ctx.save()
          ctx.beginPath(); //开始绘制
          // ctx.strokeStyle="white"
          ctx.arc(100 * scale, 90 * scale, 60 * scale, 0, Math.PI * 2, false);
          // ctx.stroke();
          ctx.clip(); //画了圆 再剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内
          ctx.drawImage(image, 40 * scale, 30 * scale, 120 * scale, 120 * scale)
          ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 可以继续绘制
        }

        var shopNameSize = 36 * scale
        var shopNameSizestr = shopNameSize + 'px Arial'

        let title = {
          x: 180 * scale,
          y: 90 * scale,
          color: '#FFFFFF',
          size: shopNameSizestr,
          align: 'left',
          baseline: 'bottom',
          text: this.data.ShopName,
          bold: true
        };
        this.drawText(ctx, title);

        var shopSMSize = 22 * scale
        var shopSMSizestr = shopSMSize + 'px Arial'

        //说明
        let content = {
          x: 180 * scale,
          y: 105 * scale,
          color: '#FFFFFF',
          size: shopSMSizestr,
          align: 'left',
          baseline: 'top',
          text: this.data.content,
          bold: false
        };
        this.drawText(ctx, content);

        ctx.save()
        //画主图      
        const imageMain = canvas.createImage();
        imageMain.src = paperUrl;
        imageMain.onload = () => {
          ctx.drawImage(imageMain, 0 * scale, 180 * scale, 580 * scale, 580 * scale)

        }


        ctx.save()
        //画二维码        
        const imageCode = canvas.createImage();
        imageCode.src = wxerWeiMaUrl;
        imageCode.onload = () => {
          ctx.drawImage(imageCode, 400 * scale, 770 * scale, 140 * scale, 140 * scale)

        }



        //画推荐人头像      
        const imageTouX = canvas.createImage();
        imageTouX.src = touXiangUrl;
        imageTouX.onload = () => {
          // 将图片绘制到 canvas 上
          ctx.save()
          ctx.beginPath(); //开始绘制
          // ctx.strokeStyle="white"
          ctx.arc(80 * scale, 840 * scale, 50 * scale, 0, Math.PI * 2, false);
          // ctx.stroke();
          ctx.clip(); //画了圆 再剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内
          ctx.drawImage(imageTouX, 30 * scale, 790 * scale, 100 * scale, 100 * scale)
          ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 可以继续绘制

        }

        var tjrNameSize = 28 * scale
        var tjrNameSizestr = tjrNameSize + 'px Arial'

        //推荐人昵称
        let userName = {
          x: 144 * scale,
          y: 838 * scale,
          color: '#838080',
          size: tjrNameSizestr,
          align: 'left',
          baseline: 'bottom',
          text: this.data.niCheng,
          bold: false
        };
        this.drawText(ctx, userName);

        //推荐说明
        var tjrSMSize = 20 * scale
        var tjrSMSizestr = tjrSMSize + 'px Arial'

        let tjContent = {
          x: 144 * scale,
          y: 850 * scale,
          color: '#b3b3b3',
          size: tjrSMSizestr,
          align: 'left',
          baseline: 'top',
          text: '为您推荐',
          bold: false
        };
        this.drawText(ctx, tjContent);


      })



  },

  drawText: function (ctx, obj) {
    ctx.save();
    ctx.fillStyle = obj.color;
    // ctx.setFontSize(obj.size);
    ctx.font = obj.size;
    // ctx.setTextAlign(obj.align);
    ctx.textAlign = obj.align;
    // ctx.setTextBaseline(obj.baseline);
    ctx.textBaseline = obj.baseline;

    // ctx.font="20px Georgia";
    // ctx.fillText(obj.text, obj.x,obj.y);

    if (obj.bold) {
      ctx.fillText(obj.text, obj.x, obj.y - 0.5);
      ctx.fillText(obj.text, obj.x - 0.5, obj.y);
    }
    ctx.fillText(obj.text, obj.x, obj.y);
    if (obj.bold) {
      ctx.fillText(obj.text, obj.x, obj.y + 0.5);
      ctx.fillText(obj.text, obj.x + 0.5, obj.y);
    }
    ctx.restore();
  },


  //保存图片权限判断
  isgetPower:function() {
    var that = this
    wx.getSetting({
      success(res) {
        if (['scope.writePhotosAlbum'] in res.authSetting) {
          // 如果授权过且同意了
          if (res.authSetting[`scope.writePhotosAlbum`]) {
            that.bindSavePaper()
          } else {
            wx.showModal({
              title: "请求授权相册存储",
              content: "需要获取您的相册存储权限，请确认授权",
              success: res => {
                if (res.confirm) {
                  wx.openSetting({
                    success: res => {
                      that.bindSavePaper()
                      console.log(res)
                    },
                    fail: err => {
                      console.log(err)
                    }
                  })
                } else if (res.cancel) {
                  console.log("你又取消了")
                }
              }
            })
          }
        } else {
          that.bindSavePaper()
        }
      }
    })




  },

  //保存图片到相册
  bindSavePaper: function () {
    wx.showLoading({
      title: '生成中...',
    })

    // var that = this

    wx.canvasToTempFilePath({
      canvas: this.data.canvas,
      x: 0,
      y: 0,
      width: this.data.canvasWidth,
      height: this.data.canvasHeight,
      destWidth: this.data.canvasdestWidth,
      destHeight: this.data.canvasdestHeight,
      success: res => {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: res => {
            // console.log(this.saveTempFilePath)
            wx.showModal({
              title: "保存成功！",
              content: "图片已保存到本地相册",
              showCancel: false,
              success(res) {

              }
            })
          },
          fail: err => {
            console.log(err)
          }
        })
      },
      fail: err => {
        console.log(err)
      }
    })
    setTimeout(() => {
      wx.hideLoading()
    }, 1000)


  }
  
})